/**
 * Created by Oswald on 2016/12/6.
 */
var selectedId = -1;
var selectedName = "";
var selectedDes = "";
var newName = "";
var newDes = "";
var loadUrl = "AddAuthority.html";
var serviceUrl = "#";
var operate = 0;
var editDivIndex = -1;
var addDivIndex = -1;
var signDivIndex = -1;

$(document).ready(function() {

    //加载数据
    LoadData();

    //新增按钮事件
    $('#addAuthority').click(function(){

        $("#modalTable").modal('show');
        $("#addAuDiv").load(loadUrl);
        $("#AddOrEditAuthorityDiv").load(loadUrl,function(){
            serviceUrl = serverPath + 'authorities/add';
            operate = 1;
        });
        addDivIndex = ShowLayer($("#AddOrEditAuthorityDiv"),"新增权限","375px","300px");
    });

    //编辑权限按钮事件
    $('#editAuthohrity').click(function(){

        $("#AddOrEditAuthorityDiv").load(loadUrl, function () {
            $('#newName').val(selectedName);
            $('#description').val(selectedDes);
            serviceUrl = serverPath + 'authorities/update';
            operate = 2;
        });
        editDivIndex = ShowLayer($("#AddOrEditAuthorityDiv"),"修改权限","375px","300px");
    })

    //删除按钮事件
    $('#deleteAuthority').click(function(){
        operate = 3;
        serviceUrl = serverPath + 'authorities/delete';
        //CallSign(100);
        Signature.Show("111",callbak);
    });

    //获取选中行数据
    function getSelectedRow() {
        var selects = $('#authorityTable').bootstrapTable('getSelections');//所有选中行的数据
        var selectData = selects[0];
        return selects[0];//返回选中行数据
    }

    //搜索按钮事件
    $('#search').click(function(){

        LoadData();
        //changeTableSelect();
    })

    //单击行触发的事件
    $('#authorityTable').on('click-row.bs.table', function (e, row, element){
        //拿到行选中的数据
        selectedId = row["id"];
        selectedName = row["name"];
        selectedDes = row["description"];
        var type = row["type"];

        $('.selected').removeClass('selected');//去除之前选中的行的，选中样式
        $(element).addClass('selected');//添加当前选中的 success样式用于区别

        //设置按钮状态
        if (type == "系统权限")
        {
            $('#editAuthohrity').attr("disabled", true);
            $('#deleteAuthority').attr("disabled", true);
        }else {
            $('#editAuthohrity').attr("disabled", false);
            $('#deleteAuthority').attr("disabled", false);
        }
    });

})

function getSelectedRow()
{
    var index = $('#authorityTable').find('tr.selected').data('index');//获得选中的行
    return $('#authorityTable').bootstrapTable('getData')[index];//返回选中行所有数据
}

//加载数据
function LoadData(){
    $('#editAuthohrity').attr("disabled", true);
    $('#deleteAuthority').attr("disabled", true);

    var name = $("#authorityName").val().trim();
    var url = serverPath + "authorities/find/Auths";
    $.ajax({
        url: url,
        data:{"name":name},
        xhrFields:{ withCredentials:true},
        traditional: true,
        type:"get",
        dataType:"json",
        success: function(result){
            var data = result.data;
            $("#authorityTable").bootstrapTable('load', data);
        },
        error:function(){
            alert("请求失败");
        },
    });
}

//弹出层
function ShowLayer(showDiv, title,width,height) {
    var divIndex = layer.open({
        //layer提供了5种层类型。可传入的值有：0（信息框，默认）；1（页面层）；2（iframe层）；3（加载层）；4（tips层）。
        // 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
        type: 1,
        //动画
        anim: 0,
        //title ：String
        //title: ['文本', 'font-size:18px;']
        //title: false 不显示标题栏
        title: [title, 'font-size:18px;font-weight:bold;'],
        //是否固定弹出
        fix: false,
        //最大小化按钮
        maxmin: false,
        //控制点击弹层外区域关闭
        shadeClose: false,
        //窗口大小 area: ['400px', '500px'] or auto 自适应大小
        area: [width, height],
        //area: '350px',
        //iframe层的url
        //content: 'http://www.baidu.com',
        content: showDiv,
        //是否允许拉伸
        resize: false,
        //浏览器滚动条
        scrollbar: false,
        zIndex: layer.zIndex, //重点1
        end: function () {
            //alert("close");
            $("#child").remove();
        }
    });
    //alert('return');
    return divIndex;
};

//保存按钮事件
function btnSave()
{
    Signature.Show("111",callbak);
    //GetEnteredAuthority();
    //CallSign(100);
}

//取消按钮事件
function cancelBtn(){
    if (operate == 1)
    {
        layer.close(addDivIndex);
    }
    if (operate == 2)
    {
        layer.close(editDivIndex);
    }
}

//签名成功后
function AfterSignature() {
    layer.close(signDivIndex);
    if(operate == 1) {
        layer.close(addDivIndex);
    }
    if(operate == 2){
        layer.close(editDivIndex);
    }
    LoadData();
}

//获取当前输入
function GetEnteredAuthority() {
    newName = $('#newName').val();
    newDes = $('#description').val();
}

//添加权限
function AddAuthority(sdid){
    var url = serviceUrl;
    var data = {"name":newName,"description":newDes,"sdid":sdid};
    var type = 'post';
    AuthorityService(url,data,type);
}

//修改权限
function UpdateAuthority(sdid){
    var url = serviceUrl;
    var data = {"id":selectedId,"name":newName,"description":newDes,"sdid":sdid};
    var type = 'put';
    AuthorityService(url,data,type);
}

//删除权限
function DeleteAuthority(sdid){
    var url = serviceUrl;
    var data = {"id":selectedId,"sdid":sdid};
    var type = 'delete';
    AuthorityService(url,data,type);
}

//权限服务
function AuthorityService(url, data,type) {

    $.ajax({
        url: url,
        type: type,
        data: data,
        xhrFields:{ withCredentials:true},
        dataType: "json",
        async: false,
        success: function (result) {
            var errCode = result.errorCode
            if(errCode == 0) {
                //alert("成功");
                AfterSignature();
            }
            else
            {
                layer.close(signDivIndex);
                layer.alert('失败：错误代码[' + errCode +']');
            }
        },
        error:function(){
            layer.close(signDivIndex);
            alert("失败");
        }
    });


}

//签名
function CallSign(signId) {
    var url = "Signature.html";
    $("#SignDiv").load(url, function () {
        SignLoad(signId, SignCallBack);
    });
    signDivIndex = ShowLayer($("#SignDiv"), '签名', '400px', '420px');
}

//回调
function SignCallBack(sdid) {
    if (operate == 1)
    {
        AddAuthority(sdid);
    }
    if(operate == 2)
    {
        UpdateAuthority(sdid);
    }
    if(operate == 3)
    {
        DeleteAuthority(sdid);
    }
}

//设置新增的行为选中行
function changeTableSelect(){
    var allData = $('#authorityTable').bootstrapTable('getData');

}

function Get(){
    var options =  $('#authorityTable').bootstrapTable('getOptions');
    alert(options.totalPages);

    if(options.pageNumber == options.totalPages)
    {
        var currentRows = $('#authorityTable').bootstrapTable('getData',true).length;
        alert(currentRows);
        if(currentRows < options.pageSize)
        {
            var total = options.totalRows;
            var rows = [];
            for(var i=1; i<=options.pageSize-currentRows;i++){
                total = total + 1;
                alert(total);
                //rowdata = {"index":total,"row":{id:total,name:"",description:"",type:""}};
                //$('#authorityTable').bootstrapTable('insertRow', {
                //    index: total,
                //    row: {
                //        id: total,
                //        name: '',
                //        description: '',
                //        type:''
                //    }
                //});


                rows.push({
                    id: total,
                    name: '',
                    description: '',
                    type:''
                });
            }

            return rows;
        }
    }
}

function Add() {
    $('#authorityTable').bootstrapTable('append', Get());
}